import re
import json

from django.contrib.auth import login, logout
from django.core.cache import cache
from django.shortcuts import render
from django.http import JsonResponse
from django import http
from django.views import View
from django_redis import get_redis_connection

from ihome.utils.views import LoginRequiredMixin
from mod.models import User, Area, House, Order
import logging
logger = logging.getLogger('django')
from decimal import Decimal



'''用户注册'''
class RegisterView(View):

    def post(self, request):
        # 接收json参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        phonecode = dict.get('phonecode')
        password = dict.get('password')
        # password2 = dict.get('password2')

        # 整体校验
        if not all([mobile, phonecode, password]):
            return JsonResponse({'errno':4103,
                                      'errmsg':'缺少必传参数'})

        # mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': 4103,
                                      'errmsg': 'mobile格式有误'})

        # sms_code检验 (链接redis数据库)
        redis_conn = get_redis_connection('verify')


        # 从redis中取值
        sms_code_server = redis_conn.get('sms_%s' % mobile)


        # 判断该值是否存在
        if not sms_code_server:
            return http.JsonResponse({'errno': 400,
                                      'errmsg': '短信验证码过期'})

        # 把redis中取得值和前端发的进行对比
        if phonecode != sms_code_server.decode():
            return http.JsonResponse({'errno':4103,
                                      'errmsg':'验证码有误'})



        # password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'errno': 4103,
                                      'errmsg': 'password格式有误'})


        # 保存到数据库
        try:
            user = User.objects.create_user(username=mobile,
                                            mobile=mobile,
                                            password=password
                                            )
        except Exception as e:
            return http.JsonResponse({'errno': 4004,
                                      'errmsg': '保存到数据库出错'})

        # 实现状态保持
        login(request, user)

        # 拼接json返回
        # return http.JsonResponse({'code': 0,
        #                           'errmsg': 'ok'})
        # 生成响应对象
        response = http.JsonResponse({'errno':0,
                                      'errmsg':'注册成功'})

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response.set_cookie('mobile',
                            user.mobile,
                            max_age = 3600 * 24 * 14)

        # 返回响应结果
        return response


# '''退出登录'''

class LogoutView(View):
    """定义退出登录的接口"""

    def delete(self, request):
        """实现退出登录逻辑"""

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = JsonResponse({'errno':0,
                                 'errmsg':'已登出'})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response

# '''修改用户名'''
class UpdateUsernameView(LoginRequiredMixin,View):

    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        name = json_dict.get('name')

        # 检验参数
        if not all([name]):
            return JsonResponse({'errno': 4103,
                                 'errmsg': '缺少必传参数'})

        user = request.user
        try:
            user.username = name
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': 400, 'errmsg': "保存数据失败"})

        return http.JsonResponse({'errno': 0, 'errmsg': "OK"})

        # 清理状态保持信息
        logout(request)

        return JsonResponse({'errno': 0,
                             'errmsg': '修改成功'})

'''地区列表'''
class AreaView(View):
    def get(self, request):
        """提供地区数据
        1.查询地区数据
        2.序列化地区数据
        3.响应地区数据
        4.补充缓存逻辑
        """

        try:
            # 1.查询地区数据
            area_model_list = Area.objects.all()
                # filter(name__isnull=False)

            # 2.整理省级数据
            area_list = []
            for area_model in area_model_list:
                area_list.append({'aid': area_model.id,
                                  'aname': area_model.name})

        except Exception as e:
              # 如果报错, 则返回错误原因:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '地区数据错误'})

        # 3.返回整理好的省级数据
        return JsonResponse({'errno': 0,
                             'errmsg': 'OK',
                             'data': area_list})


class ObtainOrderView(LoginRequiredMixin,View):
#     '''获取订单列表'''

    def get(self, request):
        # 查询数据
        user = request.user
        # 判断身份
        role = request.GET.get("role")
        if role is None:
            return JsonResponse({'errno': 400, 'errmsg': "参数错误"})

        try:
            # 查询房客订单
            if "custom" == role:
                orders = Order.objects.filter(user=user).order_by('-create_time')

            # 查询房东订单
            elif "landlord" == role:
                houses = House.objects.filter(user=user)


                houses_ids = [house.id for house in houses]
                # 取出房屋
                orders = Order.objects.filter(house_id__in=houses_ids).order_by('-create_time')
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': 400, 'errmsg': "数据查询错误"})

        orders_dict_li = []

        for order in orders:
            orders_dict_li.append({
                "amount": order.amount,
                "comment": order.comment if order.comment else "",
                "ctime": order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                "days": order.days,
                "start_date": order.begin_date.strftime("%Y-%m-%d"),
                "end_date": order.end_date.strftime("%Y-%m-%d"),
                "img_url": order.house.index_image_url if order.house.index_image_url else "",
                "order_id": order.id,
                "status": order.status,
                "title": order.house.title,
            })
        return http.JsonResponse({'errno': 0,
                                  'errmsg': "OK",
                                  'data': {"orders": orders_dict_li}})

#
class IndexView(View):
    '''首页房源推荐'''
    def get(self, request):
        houses = House.objects.all()[:5]

        data_list = []

        for house in houses:

            data_list.append({

                "house_id": house.id,
                "title": house.title,
                "img_url": house.index_image_url if house.index_image_url else ""
                # str(HouseImage.objects.get(house_id=house.id).url)
            })


        return JsonResponse({'errno': 0,
                             'errmsg': "OK",
                             'data': data_list})


class CommentOrderView(View):
    '''评价订单'''

    def put(self, request, order_id):

        # 判断是否登录




        # 接收参数
        json_data = json.loads(request.body.decode())
        comment = json_data.get('comment')
        # 校验参数
        if not comment:
            return http.HttpResponseForbidden('参数问题')
        # 实现核心逻辑
        order = Order.objects.get(id=order_id)
        order.comment = comment
        order.save()
        # 响应数据
        return http.JsonResponse({
            "errno": "0",
            "errmsg": "评论成功"})

